package org.huzhp.gateway.dynamic.route;

import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 路由模型
 * @Author: huzp
 * @CreateDate: 2020/3/12 13:25
 * @Version: 1.0
 */
public class GatewayRouteDefinition {

    private String id;
    private List<PredicateDefinition> predicates = new ArrayList();
    private List<FilterDefinition> filters = new ArrayList();
    private String uri;
    private Map<String, Object> metadata = new HashMap();
    private int order = 0;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<PredicateDefinition> getPredicates() {
        return predicates;
    }

    public void setPredicates(List<PredicateDefinition> predicates) {
        this.predicates = predicates;
    }

    public List<FilterDefinition> getFilters() {
        return filters;
    }

    public void setFilters(List<FilterDefinition> filters) {
        this.filters = filters;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public Map<String, Object> getMetadata() {
        return metadata;
    }

    public void setMetadata(Map<String, Object> metadata) {
        this.metadata = metadata;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public RouteDefinition build() {
        RouteDefinition definition = new RouteDefinition();
        if (StringUtils.isEmpty(this.id) || StringUtils.isEmpty(this.uri)) {
            throw new IllegalArgumentException("id and uri area not null");
        }
        definition.setId(this.id);
        definition.setUri(getUrl());
        definition.setFilters(this.filters);
        definition.setPredicates(this.predicates);
        definition.setMetadata(this.metadata != null ? this.metadata : new HashMap<>());
        definition.setOrder(this.order);

        return definition;
    }

    public URI getUrl() {
        URI uri = null;
        if (this.uri.startsWith("http")) {
            uri = UriComponentsBuilder.fromHttpUrl(this.uri).build().toUri();
        } else {
            // uri为 lb://consumer-service 时使用下面的方法
            uri = URI.create(this.uri);
        }
        return uri;
    }
}
